<template>
	<view>
		<web-view :src="webviewUrl" @message="handleWebviewMessage" ></web-view>
		<!--  <web-view :src="webviewUrl" ></web-view> -->
		<!-- <view>
			{{webviewUrl}}
		</view> -->
	</view>
	
</template>

<script>
	import request from '@/api/index'
import backtop from '../../uni_modules/uview-ui/libs/config/props/backtop';
  export default {
    data() {
      return {
        webviewUrl: '',
		shareOptionsObj:{},
		apiinfo:{},
      };
    },
    onLoad(options) {
		const q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
		const scancode_time = parseInt(options.scancode_time) // 获取用户扫码时间 UNIX 时间戳
		
		if(options.q && !options.link){
			options.link=encodeURIComponent(q);
			console.log("@@@@@@",q,options);
			this.receivePathParams(options);
		}else{
			this.receivePathParams(options);
			options.link=encodeURIComponent(this.webviewUrl)
			
			console.log("链接",this.webviewUrl,options.link);
		}

		
    },
    methods: {
      // 接收路径参数
      receivePathParams(options) {
        const params = options;
		let link = decodeURIComponent(params.link);
		let link_params1=this.urlParse(link);
		
		console.log("解码1",link);
		
		if(link_params1 && link_params1.decode==1){
			console.log("跳过解码");
		}else{
			if(link.indexOf('%')>-1){
				link=decodeURIComponent(link);
			}
			console.log("没跳过");
		}

		let link_params=this.urlParse(link);
		console.log("解码2",link);

        switch (params.type) {
          case 'news':
            const token = uni.getStorageSync('token')
            // 测试版
            // this.webviewUrl =
            //   `http://intelligencevillage.dev.sj33333.com/index.php/Api/News/newsshow?news_id=${params.id}&area_id=${this.areaId}&token=${token}`;

            // 正式版
            this.webviewUrl =
              `https://intelligencevillage.sj33333.com/Api/News/newsshow?news_id=${params.id}&area_id=${this.areaId}&token=${token}`
            break;
          case 'subject':
            this.webviewUrl = `https://yimentong.sj33333.com/app/LearnIndex/${params.id}?area_id=${this.areaId}`;
            break;
          case 'pdf':
            this.webviewUrl = link;
            break
          default:
			//判断是否需要登录，然后跳转登录页面
			if (link_params && link_params.l == 1) {
				let token = this.$store.state.token;
				console.log("!!!!!",link_params.token);
				if(!link_params.token){
					
					if (token && token.length) {
						if (link.includes('?') && link.includes('=')) {
							link += `&token=${token}`
						} else {
							link += `?token=${token}`
						}
					}else{
						let new_link='/pages/index/webview?link='+params.link;
						uni.redirectTo({
							url: `/pages/user/login?redirect=${encodeURIComponent(new_link)}`
						})
						break;
					}
				}
			}
			
			//默认添加地区id
			if(!link_params.area_id){
				if (link.includes('?') && link.includes('=')) {
					link += `&area_id=${this.areaId}`
				} else {
					link += `?area_id=${this.areaId}`
				}
			}
			
			//如果有背景参数则修改头部背景
			if(link_params.backgroundColor){
				console.log("######头部背景",link_params.backgroundColor)
				uni.setNavigationBarColor({
				    frontColor: '#ffffff',
				    backgroundColor: '#'+link_params.backgroundColor,
				})
			}
			
			if (link_params && link_params.l == 3) {
				
				let token = this.$store.state.token;
				if(!token){
					let new_link='/pages/index/webview?link='+params.link;
					uni.redirectTo({
						url: `/pages/user/login?redirect=${encodeURIComponent(new_link)}`
					})
					break;
				}
				
				uni.showLoading({
					title: '登录中',
					mask: true
				})
				
				console.log("#######123123",link_params.api);
				//联合登录需要获取对应token
				request({
					url: link_params.api?link_params.api:'/member/connectSmarttown',
					method: 'POST',
				}).then(res => {
					let conne_token=res.data.token;
					if (link.includes('?') && link.includes('=')) {
						link += `&token=${conne_token}`
					} else {
						link += `?token=${conne_token}`
					}
					this.webviewUrl=link;
					options.link=encodeURIComponent(this.webviewUrl)
					uni.hideLoading();
				});
				break;
			}
			
			//判断是否需要获取当前坐标
			if(link_params.getlocation){
				
				let that=this;
				uni.getLocation({
					type: 'wgs84',
					success: function (res) {
						console.log("坐标",res);
						if (link.includes('?') && link.includes('=')) {
							link += `&lat=${res.latitude}&lng=${res.longitude}`
						} else {
							link += `?lat=${res.latitude}&lng=${res.longitude}`
						}
						that.webviewUrl = link;
						
					},
					fail(err) {
						
						uni.showModal({
							title: "禁止授权获取当前坐标，会导致功能无法正常使用",
							confirmText: '确定',
							showCancel: false,
							success:(res=> {
								that.webviewUrl = link;
							})
						})
						
					}
				});
				
			}else{
				this.webviewUrl = link;
			}
            
            break;
        }

        console.log(111, this.webviewUrl);
      },
	  urlParse(url) {
	  	let obj = {}
	  	let reg = /[?&][^?&]+=[^?&]+/g
	  	let arr = url.match(reg)
	  	// ['?id=12345','&a=b']
	  	if (arr) {
	  		arr.forEach((item) => {
	  			let tempArr = item.substr(1).split('=')
	  			let key = decodeURIComponent(tempArr[0])
	  			let val = decodeURIComponent(tempArr[1])
	  			obj[key] = val
	  		})
	  	}
	  	return obj
	  },
	 //  onShareAppMessage(res) {
		// console.log("@@@@@",res)
		// //h5返回分享信息
		// if (this.shareOptionsObj.path) {
		// 	console.log("##触发分享")
		// 	//执行对应api回调
		// 	if(this.apiinfo.api){
				
		// 		this.apirequest().then(res=>{
		// 			console.log("@@@@@");
		// 			if(res.data.info){
		// 				uni.showModal({
		// 					title: '温馨提示',
		// 					content: res.data.info,
		// 					showCancel: false,
		// 					confirmText: '知道了'
		// 				})
		// 			}
		// 			return this.shareOptionsObj;  
					
		// 		}).catch(err=>{
		// 			// if(err.data.info){
		// 			// 	uni.showModal({
		// 			// 		title: '温馨提示',
		// 			// 		content: err.data.info,
		// 			// 		showCancel: false,
		// 			// 		confirmText: '知道了'
		// 			// 	})
		// 			// }
		// 			return this.shareOptionsObj;  
		// 		})
		// 	}else{
		// 		return this.shareOptionsObj;  
		// 	}
		  
		// } else {
		// 	  // 内置触发
		// 	  const pages = getCurrentPages() // 获取当前页面栈
		// 	  const curPage = pages[pages.length - 1] // 获取当前页面

		// 	  if (curPage.options) {

		// 		//判断是否有token,有的话就清除token
		// 		if(curPage.route=="pages/index/webview"){
		// 			let webViewUrl=res.webViewUrl;
		// 			let params=this.urlParse(webViewUrl);

		// 			if (params && params.l == 1) {
		// 				delete params.token
						
		// 				let new_link="";
		// 				for(var item in params){
		// 					if(new_link==""){
		// 						new_link=`?${item}=${params[item]}`
		// 					}else{
		// 						new_link+=`&${item}=${params[item]}`
		// 					}
		// 				}
		// 				curPage.options.link=encodeURIComponent(webViewUrl.split("?")[0]+new_link);
		// 			}
		// 		}
				  
		// 		let queryList = []
		// 		for (const [k, v] of Object.entries(curPage.options)) {
		// 		  queryList.push(`${k}=${v}`)
		// 		}

		// 		this.shareConfig.path = `/${curPage.route}?${queryList.join('&')}` // 需要以/开头
		// 	  } else {
		// 		this.shareConfig.path = `/${curPage.route}` // 需要以/开头
		// 	  }
		// 	  console.log("%%%%",this.shareConfig);

		// 	  return this.shareConfig
		// 	}
		

	 //  },
	  handleWebviewMessage(e) {
		  console.log("@@@@",e)
	      const obj = e.detail.data[e.detail.data.length - 1]
	      if (obj.type === 'share') {
			this.shareOptionsObj= obj.config;
	      }
		  
		  if(obj.type==='back'){
			  if(obj.url){

				  let pages = getCurrentPages();
				  let prevPage = pages[pages.length - 2];
				  // console.log("back事件111",prevPage,obj.url);
				  // prevPage.setData({
				  // 	webviewUrl: obj.url
				  // })
				  prevPage.$vm.toNewUrl(`/pages/index/webview?link=${encodeURIComponent(obj.url)}`)
				  
				  // uni.navigateBack({
				  //   delta: 1,
				  //   success: function (res) {
						// prevPage.$vm.toNewUrl(`/pages/index/webview?link=${encodeURIComponent(obj.url)}`)
				  //   }
				  // })
				  
			  }else{
				  uni.navigateBack({
				    delta: 1
				  })
			  }
		  }
		  console.log("$$$$$$",this.shareOptionsObj);
		  
		  if(obj.apiinfo){
			  this.apiinfo=obj.apiinfo;
		  }
		},
		apirequest(){
			return request({
				url: this.apiinfo.api,
				method: 'POST',
				data: this.apiinfo.params
			})
		},
		toNewUrl(url){
			uni.redirectTo({
				url: url,
			});
		},

	  
    }
  };
</script>

<style lang="scss" scoped></style>